package Thread;
//为了简单，不写作泛型的形式，考虑存储的元素就是单纯的String
class MyBlockingQueue{
    private String[] elems;
    private int head;
    private int tail;
    private int useSize;
    //准备一个锁对象,使用this也可以
    Object locker = new Object();
    //构造方法
    public  MyBlockingQueue(int capacity){
        elems = new String[capacity];
    }
    //入队列
    public void put(String elem) throws InterruptedException {
        //加锁加到这里本质上和加锁加到方法上是一样的，加到方法上是给this加锁，此处是给locker加锁
        synchronized (locker) {
            while(useSize >= elems.length) {
                //队列满了
                //后续需要让这个代码能够阻塞
                locker.wait();
            }
            //新的元素要能够放到tail位置上
            elems[tail] = elem;
            tail++;
            if (tail >= elems.length) {
                tail = 0;
            }
            useSize++;
            //入队列成功后唤醒
            locker.notify();
        }
    }

    //出队列
    public String take() throws InterruptedException {
        String elem = null;
        synchronized (locker) {
            while (useSize == 0) {
                //队列空了
                //后续也需要让这个代码阻塞
                locker.wait();
            }
            //取出head位置的元素并且返回
          elem = elems[head];
            head++;
            if (head == elems.length) {
                head = 0;
            }
            useSize--;
            //元素出队列成功之后，唤醒
            locker.notify();
        }
            return elem;

    }
}
public class ThreadDemo29 {
    public static void main(String[] args) throws InterruptedException {
        MyBlockingQueue queue = new MyBlockingQueue(1000);
//        queue.put("666");
//        queue.put("777");
//        queue.put("888");
//        queue.put("999");
//        String elem = queue.take();
//        System.out.println(elem);
//        String elem1 = queue.take();
//        System.out.println(elem1);
//        String elem2 = queue.take();
//        System.out.println(elem2);
//        String elem3 = queue.take();
//        System.out.println(elem3);
        //生产者
        Thread t1 = new Thread(()->{
            int n = 1;
            try {
                while(true) {
                    queue.put(String.valueOf(n));
                    System.out.println("生产元素:" + n);
                    n++;
                    Thread.sleep(500);
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });
        //消费者
        Thread t2 = new Thread(()->{
            try {
                while (true) {
                    String n = queue.take();
                    System.out.println("消费元素" + n);
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });
        t1.start();
        t2.start();
    }
}
